package com.gbiac.modules.monitor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gbiac.modules.monitor.entity.UserSeat;
import com.gbiac.modules.monitor.mapper.UserSeatMapper;
import com.gbiac.modules.monitor.param.UserSeatParam;
import com.gbiac.modules.monitor.service.IUserSeatService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 用户席位绑定关系
 * @Author: jeecg-boot
 * @Date:   2024-12-01
 * @Version: V1.0
 */
@Service
public class UserSeatServiceImpl extends ServiceImpl<UserSeatMapper, UserSeat> implements IUserSeatService {

    @Resource
    private UserSeatMapper userSeatMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserSeat(UserSeatParam userSeatParam) {
        if (StringUtils.isBlank(userSeatParam.getUserId())) {
            throw new JeecgBootException("用户id不能为空");
        }
        // 全部删除
        remove(new LambdaQueryWrapper<UserSeat>().eq(UserSeat::getUserId, userSeatParam.getUserId()));
        List<String> directlySeatIdList = userSeatParam.getDirectlySeatIdList();
        if (CollectionUtils.isNotEmpty(directlySeatIdList)) {

            List<UserSeat> userSeatList = directlySeatIdList.stream().map((seatId) -> {
                UserSeat userSeat = new UserSeat();
                userSeat.setUserId(userSeatParam.getUserId());
                userSeat.setSeatId(seatId);
                userSeat.setLoginType(UserSeat.LoginType.DIRECTLY);

                return userSeat;
            }).collect(Collectors.toList());
            saveBatch(userSeatList);
        }

        List<String> studySeatIdList = userSeatParam.getStudySeatIdList();
        if (CollectionUtils.isNotEmpty(studySeatIdList)) {

            List<UserSeat> userSeatList = studySeatIdList.stream().map((seatId) -> {
                UserSeat userSeat = new UserSeat();
                userSeat.setUserId(userSeatParam.getUserId());
                userSeat.setSeatId(seatId);
                userSeat.setLoginType(UserSeat.LoginType.STUDY);

                return userSeat;
            }).collect(Collectors.toList());
            saveBatch(userSeatList);
        }
    }
}
